package sale.wxb.loveshopping.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;

import java.io.IOException;

/**
 * 自定义Long序列化器
 * 超出前端最大数字转为字符串
 */
@JacksonStdImpl
public final class BigNumberSerializer extends JsonSerializer<Long> {
    public static final BigNumberSerializer INSTANCE = new BigNumberSerializer();
    // 根据 JS Number.MAX_SAFE_INTEGER 与 Number.MIN_SAFE_INTEGER 得来
    private static final long MAX = 9007199254740991L;
    private static final long MIN = -9007199254740991L;

    public BigNumberSerializer() {
    }

    @Override
    public void serialize(Long aLong, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (aLong > MIN && aLong < MAX) {
            jsonGenerator.writeNumber(aLong);
        } else {
            jsonGenerator.writeString(aLong.toString());
        }
    }
}
